package cn.jiyun.user.controller;

import cn.jiyun.user.pojo.Users;
import cn.jiyun.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

//    页面跳转  add  update  login

    @GetMapping("/{page}")
    public String toPage(@PathVariable("page") String page) {
        return page;
    }

//   添加用户

    @RequestMapping("/addUser")
    public String addUser(Users users) {
        userService.saveUser(users);
        return "ok";
    }
//   修改用户

    @RequestMapping("/updateUser")
    public String updateUser(Users users,Model model) {
        userService.updateUser(users);
        List<Users> users1 = userService.findAll();
        model.addAttribute("list",users1);
        return "list";
    }
//    查询所有用户

    @RequestMapping("/findAll")
    public String findAll(Model model) {
        List<Users> list = userService.findAll();
        model.addAttribute("list", list);
        return "list";
    }
    //  根据Id查询所有用户

    @RequestMapping("/findById")
    public String findById(String id,Model model) {
        Users users = userService.findById(id);
        model.addAttribute("list",users);
        return "update";
    }

    //    登录方法
    @PostMapping("/login")
    public String login(String name, String pwd, Model model) {
        Users users = userService.login(name, pwd);
        model.addAttribute("users", users);
        return "ok";
    }
    //删除
    @GetMapping("del")
    public String del(String id,Model model){
        userService.deleteUser(id);
        List<Users> users = userService.findAll();
        model.addAttribute("list",users);
        return "list";
    }
}
